<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexUserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }

    public function index(IndexUserRequest $request)
    {
        $query = User::query();

        $query->when($request->filled('username'), function ($query) use ($request) {
            $username = $request->input('username');
            return $query->where(function ($subquery) use ($username) {
                $subquery->where('username', 'like', "%$username%");
            });
        })->when($request->filled('status'), function ($query) use ($request) {
            return $query->where('status', $request->input('status'));
        });

        $data = $query->orderBy('created_at', 'DESC')->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response =  UserResource::collection($data);
        $total = $response->total();
        return $this->success('查询成功', $response, $total);
    }

    /**
     * 更改用户状态
     *
     * @param Request $request
     * @param [type] $id
     * @return 
     */
    public function updateStatus(Request $request, $id)
    {
        $user = User::findOrFail($id);
        $this->authorize('updateStatus');

        Validator::make($request->input(), [
            'status' => ['required', 'in:1,0']
        ])->validate();
        $user->status = $request->input('status');
        $user->saveOrFail();
        return $this->success('状态修改成功', $user);
    }

    /**
     * v2  修改用户信息
     *
     * @param Request $request
     * @param User $user
     * @param [type] $id
     * @return 
     */
    public function update(Request $request, User $user, $id)
    {
        $user = $user->findOrFail($id);
        $this->authorize('update', $user);

        $user->fill($request->input());
        $user->saveOrFail();
        return $this->success('更新成功', $user);
    }
    /**
     * v2  修改用户密码
     *
     * @param Request $request
     * @param User $user
     * @param [type] $id
     * @return 
     */
    public function password(Request $request, User $user, $id)
    {
        $user = $user->findOrFail($id);
        $this->authorize('update', $user);
        Validator::make([
            'password' => $request->input('password')
        ], [
            'password' => ['required']
        ])->validate();

        $user->password = Hash::make($request->password);
        $user->saveOrFail();
        return $this->success('更新成功');
    }
}
